package netty.builder;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public enum OS {
    windows, linux, mac, unknown;

    private static OS current;
    private static volatile EventLoopGroup defaultLoopGroup;

    public static OS detect() {
        if (current != null) {
            return current;
        }

        String osName = System.getProperty("os.name");
        if (osName == null) {
            current = unknown;
        } else {
            osName = osName.toLowerCase();
            if (osName.contains("linux")) {
                current = linux;
            } else if (osName.contains("windows")) {
                current = windows;
            } else if (osName.contains("mac os")) {
                current = mac;
            } else {
                current = unknown;
            }
        }

        return current;
    }

    public static EventLoopGroup newEventLoopGroup() {
        // return OS.detect() == OS.linux ? new EpollEventLoopGroup() : new NioEventLoopGroup();
        return new NioEventLoopGroup();
    }

    static EventLoopGroup defaultLoopGroup() {
        if (defaultLoopGroup == null) {
            synchronized (OS.class) {
                if (defaultLoopGroup == null) {
                    defaultLoopGroup = newEventLoopGroup();
                }
            }
        }
        return defaultLoopGroup;
    }

    public static Class<? extends ServerSocketChannel> getDefaultServerChannelClass() {
//        return OS.detect() == OS.linux ? EpollServerSocketChannel.class : NioServerSocketChannel.class;
        return NioServerSocketChannel.class;
    }

    public static Class<? extends SocketChannel> getDefaultClientChannelClass() {
//        return OS.detect() == OS.linux ? EpollSocketChannel.class : NioSocketChannel.class;
        return NioSocketChannel.class;
    }
}
